package com.yc.security.authentication;

import com.alibaba.fastjson.JSON;
import com.yc.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 无权访问处理器
 * @author kukaha
 * @version 1.0.0
 * @ClassName JwtAuthenticationAccessDenied.java
 * @Description TODO
 * @createTime 2021年03月27日 00:18:00
 */
@Component("customAuthenticationAccessDenied")
public class JwtAuthenticationAccessDenied implements AccessDeniedHandler {

    Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        logger.info("authentication: " + JSON.toJSONString(e));
        Result result = Result.error().code(HttpServletResponse.SC_FORBIDDEN).message("无权访问");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(result.buildString());
    }
}
